package com.heima.wemedia.controller.v1;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-11 15:19
 */
@RestController
@RequestMapping("/api/v1/material")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    @PostMapping("/upload_picture")
    public ResponseResult uploadPicture(@RequestParam("multipartFile") MultipartFile multipartFile){
        //1.校验参数
        if(multipartFile.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmMaterial material = materialService.upload(multipartFile);

        return ResponseResult.okResult(material);
    }

    @PostMapping("/list")
    public ResponseResult list(@RequestBody WmMaterialDto dto){
        dto.checkParam(); //将size page 设置成正确的范围

        //查询
        Page<WmMaterial> wmMaterialPage = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId()) //只获取当前登录人图片
                .orderByDesc(WmMaterial::getCreatedTime);

        //特殊条件 校验是否收藏
        if(Objects.equals(dto.getIsCollection(),(short)1)){
            wrapper.eq(WmMaterial::getIsCollection,(short)1);
        }

        Page<WmMaterial> page = materialService.page(wmMaterialPage, wrapper);

        PageResponseResult result =
                new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());

        result.setData(page.getRecords());
        return result;
    }
}
